/*
 3 aug 2010 by Henry
 - converting a byte value0-255 in binary form and decomposed into 4 data
 variable=D1|D2|D3|D4 D1 highest 2 bits, D4 lowest 2 bits
 this program receive ASCII code from serial monitor and transfer into above data form
 */
int v = 0, D1, D2, D3, D4;
int ppm = 2;// define pin connect to ppm of GWS
unsigned int Level[4] = { 1125, 1375, 1625, 1875 };// 4 level of ms, 00=1.125ms/01=1.375ms/10=1.625ms/11=1.875ms
unsigned long startTime, endTime;
void setup() {
	Serial.begin(9600);
	pinMode(ppm, OUTPUT);
}
void loop() {

	if (Serial.available() > 0) {// if data available


		v = Serial.read(); // read the incoming byte:
		Serial.print("v:");
		Serial.println(v, BIN);
		D4 = (v & B00000011);
		D3 = (v & B00001100) >> 2;
		D2 = (v & B00110000) >> 4;
		D1 = (v & B11000000) >> 6;
		Serial.print("D1:");
		Serial.println(D1);
		Serial.print("D2:");
		Serial.println(D2);
		Serial.print("D3:");
		Serial.println(D3);
		Serial.print("D4:");
		Serial.println(D4);
		delay(200);
	}// end of if

	// start to forming ppm signal based on D1~D4
	D300();
	delayMicroseconds(Level[D1] - 300);
	D300();
	delayMicroseconds(Level[D2] - 300);
	D300();
	delayMicroseconds(Level[D3] - 300);
	D300();
	delayMicroseconds(Level[D4] - 300);
	D300();
	delay(10);// delay 10 ms
}// end of loop()


void D300() { //funcion to creat a 300us high pluse
	digitalWrite(ppm, HIGH);
	delayMicroseconds(300);
	digitalWrite(ppm, LOW);
} //end of 300us
